package com.stx.blog.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.stx.blog.dao.CategoryDao;
import com.stx.blog.entity.CategoryEntity;
import com.stx.blog.vo.CategoryVo;


public class CategoryDaoImpl extends JdbcDaoSupport implements CategoryDao{
	
	public List<CategoryEntity> list(CategoryVo criteria) {

		String sql = "select * from category";

		JdbcTemplate jt = getJdbcTemplate();

		List<CategoryEntity> stuList = jt.query(sql, new CategoryRowMapper());

		return stuList;
	}

	class CategoryRowMapper implements RowMapper {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			
			CategoryEntity entity = new CategoryEntity();

			
			entity.setId(rs.getInt("id"));
			entity.setName(rs.getString("name"));
			
			return entity;
		}
	}
	
	@Override
	public void delCategory(Integer id) {

		JdbcTemplate jt = getJdbcTemplate();

		String sql = "delete from category where id = ?";

		
		Object[] args = { id };

		jt.update(sql, args);

	}

	
	@Override
	public void addCategory(CategoryVo category) {

		JdbcTemplate jt = getJdbcTemplate();

		String sql = "insert into category(id,name) values(?,?)";

		Object[] args = { category.getId(), category.getName()
				};

		jt.update(sql, args);

	}

	@Override
	public CategoryEntity findCategoryById(Integer id) {

		JdbcTemplate jt = getJdbcTemplate();

		String sql = "select * from category where id = ?";

		Object[] args = { id };

		CategoryEntity categoryEntity = (CategoryEntity) jt.queryForObject(sql,
				args, new CategoryRowMapper());

		return categoryEntity;
	}

	@Override
	public void updateCategory(CategoryVo category) {

		JdbcTemplate jt = getJdbcTemplate();

		String sql = "update category set name= ? where id = ?";

		Object[] args = { category.getName(), category.getId()
				 };

		jt.update(sql, args);

	}

}
